/**
 * 
 */

package com.chengyu.eyc.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.StrictHttpFirewall;

import com.chengyu.eyc.config.security.EycAuthenticationFailureHandler;
import com.chengyu.eyc.config.security.EycAuthenticationSuccessHandler;
import com.chengyu.eyc.config.security.EycCustomLogoutHandler;
import com.chengyu.eyc.config.security.EycLoginAuthenticationFilter;
import com.chengyu.eyc.config.security.EycUserDetailsAuthenticationProvider;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author kevin
 *
 */
@Slf4j
@Configuration
@EnableWebSecurity
public class EycWebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    /**
     * 登录页面
     */
    private static final String LOGIN_URL = "/login";

    /**
     * 忽略安全校验
     */
    private static final String[] IGNORE_RESOURCES = new String[] {"/", "/js/**", "/css/**", "/font-awesome/**", "/fonts/**", "/images/**", "/assets/**", "/il5AIHBIL9.txt","/wechat/**"};

    /**
     * 忽略安全校验
     */
    private static final String[] PERMIT_URLS = {"/","/verifyCode" ,"/login/**","/wechat/**", "/file/**", "/msg/**"};
    
    @Value("${spring.profiles}")
    private String  env;

    @Autowired
    private EycUserDetailsAuthenticationProvider eycUserDetailsAuthenticationProvider;

    @Autowired
    private EycAuthenticationSuccessHandler eycAuthenticationSuccessHandler;

    @Autowired
    private EycCustomLogoutHandler eycCustomLogoutHandler;

    @Autowired
    private EycAuthenticationFailureHandler eycAuthenticationFailureHandler;



    @Bean
    public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
        StrictHttpFirewall firewall = new StrictHttpFirewall();
        // 此处可添加别的规�目前只设�允许�//
        firewall.setAllowUrlEncodedDoubleSlash(true);
        return firewall;
    }

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder)
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(eycUserDetailsAuthenticationProvider);
    }

    /**
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // http.authorizeRequests().antMatchers(PERMIT_URLS).permitAll().anyRequest().authenticated().and().formLogin().loginPage(LOGIN_URL).loginProcessingUrl(LOGIN_URL)
        // .successHandler(eycAuthenticationSuccessHandler.setDefaultTargetUrl("/index", Boolean.FALSE))
        // .failureHandler(eycAuthenticationFailureHandler.setFailureUrl("/login?error=true")).permitAll()
        // .and().csrf().disable();

        http.addFilterBefore(new EycLoginAuthenticationFilter(LOGIN_URL), UsernamePasswordAuthenticationFilter.class).authorizeRequests().antMatchers(PERMIT_URLS).permitAll().anyRequest().authenticated()
            .and().formLogin().loginPage(LOGIN_URL)// 登录
            .successHandler(eycAuthenticationSuccessHandler.setDefaultTargetUrl("/index", Boolean.FALSE))// 登录成功
            .failureHandler(eycAuthenticationFailureHandler.setFailureUrl("/login?error=true"))// 登录失败
            .and().logout().addLogoutHandler(eycCustomLogoutHandler).logoutSuccessUrl(LOGIN_URL).permitAll(); // 注销
        // // 无权�
        // http.exceptionHandling().accessDeniedHandler(new GenericAccessDeniedHandler())
        // // 未认�超时)
        // .and().exceptionHandling()
        // .defaultAuthenticationEntryPointFor(new JsonAuthenticationEntryPoint(), JsonRequestMatcher.INSTANCE)
        // .defaultAuthenticationEntryPointFor(new LoginUrlAuthenticationEntryPoint("/login?expired"),
        // PageRequestMatcher.INSTANCE);

        http.headers().frameOptions().sameOrigin().and().csrf().disable();
        log.info("运行环境[]",env);
        if(StrUtil.equalsIgnoreCase(env, "prod")) {
            http.requiresChannel().anyRequest().requiresSecure();  
        }
    
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(IGNORE_RESOURCES);
    }

}
